﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace Ev.Answer
{
    public partial class AnswerForm : Form
    {
        SoundPlayer soundplayer = new SoundPlayer();

        public int sIndexType { get; set; }

        /// <summary>
        /// 是否可以抢答
        /// </summary>
        public bool isQD { get; set; }

        /// <summary>
        /// 当前答题的索引
        /// </summary>
        public int AnswerIndex { get; set; }

        /// <summary>
        /// 当前分类的问题集合
        /// </summary>
        public XmlNodeList nodeListAnswer { get; set; }

        /// <summary>
        /// 正确的回答集合
        /// </summary>
        List<XmlNode> nodeListOk = new List<XmlNode>();

        //初始化xml
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement xmlRoot;

        /// <summary>
        /// 倒计时指针--开始抢答
        /// </summary>
        public int Countdown { get; set; }

        /// <summary>
        /// 倒计时指针--剩余答题时间
        /// </summary>
        public int CountdownSY { get; set; }

        /// <summary>
        /// 当前抢答的编号
        /// </summary>
        public int userIndex { get; set; }

        /// <summary>
        /// 答题总分
        /// </summary>
        public double MaxNum { get; set; }
        /// <summary>
        /// 单题分数
        /// </summary>
        public double danNum { get; set; }

        public AnswerForm()
        {
            InitializeComponent();
        }



        private void AnswerForm_Load(object sender, EventArgs e)
        {

            //启动线程
            MessageBoxHelper.IsWorking = true;
            MessageBoxHelper.FindAndKillWindow();

            this.KeyUp += AnswerForm_KeyUp;
            this.KeyPreview = true;

            MaxNum = 100;

            if (File.Exists(StaticData.xmlUrlPath))
                xmlDoc.Load(StaticData.xmlUrlPath);
            else
                xmlDoc.LoadXml("<XmlConfig />");
            xmlRoot = (XmlElement)xmlDoc.ChildNodes[1];

            var xmlNode = xmlRoot.SelectSingleNode(StaticData.TypeNode + "[@sIndex='" + sIndexType + "']");
            if (xmlNode == null) return;
            //问题列表
            nodeListAnswer = xmlNode.SelectNodes(StaticData.QuestionNode);

            danNum = MaxNum / nodeListAnswer.Count;

            ///答案按钮注册点击事件
            btnA.Click += BtnAnswer_Click;
            btnB.Click += BtnAnswer_Click;
            btnC.Click += BtnAnswer_Click;
            btnD.Click += BtnAnswer_Click;
            btnE.Click += BtnAnswer_Click;
            btnF.Click += BtnAnswer_Click;

            panel答案.Visible = false;

            timer1.Interval = 1000;
            timer1.Tick += Timer1_Tick;

            timer2.Tick += Timer2_Tick;
            timer2.Interval = 1000;

            AnswerIndex = 0;
            InitAnswer();

        }

        private void BtnAnswer_Click(object sender, EventArgs e)
        {
            if (userIndex == 0)
            {
                return;
            }
            isQD = false;

            //panel答案.Enabled = false;
            timer1.Stop();
            timer2.Stop();
            Button btn = (Button)sender;
            var isOK = Convert.ToBoolean(btn.Tag);
            if (isOK)
            {
                //回答正确
                var nodeQ = nodeListAnswer[AnswerIndex];
                nodeListOk.Add(nodeQ);
                CountNum(danNum);
                //播放正确提示音
                soundplayer.SoundLocation = StaticData.soundOk;

            }
            else
            {


                CountNum(-danNum);
                soundplayer.SoundLocation = StaticData.soundFail;
            }
            userIndex = 0;
            soundplayer.Load();
            soundplayer.Play();

            foreach (Button item in panel答案.Controls)
            {
                if (item.Tag == btn.Tag)
                {
                    MessageBoxHelper.FindAndKillWindow();
                    MessageBox.Show("回答正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    break;
                }
                else if (Convert.ToBoolean(item.Tag))
                {
                    MessageBox.Show("回答错误！正确答案为：" + item.Text, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }
            }

           
            Thread.Sleep(1500);

            AnswerIndex++;
            if (AnswerIndex >= nodeListAnswer.Count)
            {
                List<modelKV> mm = new List<modelKV>();

                mm.Add(new modelKV() { key = "第一代表队", value = Convert.ToDouble(labelNo1.Text) });
                mm.Add(new modelKV() { key = "第二代表队", value = Convert.ToDouble(labelNo2.Text) });
                mm.Add(new modelKV() { key = "第三代表队", value = Convert.ToDouble(labelNo3.Text) });
                //mm.Add(new modelKV() { key = "第四代表队", value = Convert.ToDouble(labelNo4.Text) });
                //mm.Add(new modelKV() { key = "第五代表队", value = Convert.ToDouble(labelNo5.Text) });
                //mm.Add(new modelKV() { key = "第六代表队", value = Convert.ToDouble(labelNo6.Text) });
                //mm.Add(new modelKV() { key = "第七代表队", value = Convert.ToDouble(labelNo7.Text) });
                //mm.Add(new modelKV() { key = "第八代表队", value = Convert.ToDouble(labelNo8.Text) });

                mm.Sort((x, y) => y.value.CompareTo(x.value));

                var strMsg = "当前答题完成：\r\n";
                //已抢答完成
                for (int i = 0; i < mm.Count(); i++)
                {
                    var item = mm[i];
                    strMsg += "第" + (i + 1) + " 名：" + item.key + "(" + item.value + "分)\r\n";
                }

                //MessageBox.Show(strMsg);
                AnswerSuccess asu = new AnswerSuccess();
                asu.strNumber = strMsg;
                asu.ShowDialog();
                this.Close();
                return;
            }
            InitAnswer();
        }
        


        public void InitAnswer()
        {
            panel答案.Visible = false;

            btnA.Visible = false;
            btnB.Visible = false;
            btnC.Visible = false;
            btnD.Visible = false;
            btnE.Visible = false;
            btnF.Visible = false;

            if (nodeListAnswer == null || nodeListAnswer.Count == 0 || nodeListAnswer.Count == AnswerIndex)
            {
                return;
            }

            var nodeQ = nodeListAnswer[AnswerIndex];
            labelTitle.Text = "■" + nodeQ.Attributes["Name"].Value;
            label2.Text = "第" + (AnswerIndex + 1) + "题(共" + nodeListAnswer.Count + "题) ";
            //MessageBox.Show("请做好准备，预备开始抢答");

            Countdown = 3;
            labelDate.Text = Countdown.ToString();
            timer1.Start();
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (Countdown > 0)
            {
                switch (Countdown)
                {
                    case 3:
                        { soundplayer.SoundLocation = StaticData.sound3; }
                        break;
                    case 2:
                        soundplayer.SoundLocation = StaticData.sound2;
                        break;
                    case 1:
                        soundplayer.SoundLocation = StaticData.sound1;
                        break;
                    default:
                        break;
                }
                soundplayer.Load();
                soundplayer.Play();
                labelDate.Text = Countdown.ToString();
                Countdown--;
                return;
            }
            isQD = true;

            this.labelCDown.Text = "30";

            var nodeQ = nodeListAnswer[AnswerIndex];
            var nodeA = nodeQ.SelectSingleNode(StaticData.AnswerNode + "[@cNo='A']");
            if (nodeA != null && !string.IsNullOrEmpty(nodeA.InnerText)) { btnA.Text = "A." + nodeA.InnerText; btnA.Tag = nodeA.Attributes["isOK"].Value; btnA.Visible = true; }

            var nodeB = nodeQ.SelectSingleNode(StaticData.AnswerNode + "[@cNo='B']");
            if (nodeB != null && !string.IsNullOrEmpty(nodeB.InnerText)) { btnB.Text = "B." + nodeB.InnerText; btnB.Tag = nodeB.Attributes["isOK"].Value; btnB.Visible = true; }

            var nodeC = nodeQ.SelectSingleNode(StaticData.AnswerNode + "[@cNo='C']");
            if (nodeC != null && !string.IsNullOrEmpty(nodeC.InnerText)) { btnC.Text = "C." + nodeC.InnerText; btnC.Tag = nodeC.Attributes["isOK"].Value; btnC.Visible = true; }

            var nodeD = nodeQ.SelectSingleNode(StaticData.AnswerNode + "[@cNo='D']");
            if (nodeD != null && !string.IsNullOrEmpty(nodeD.InnerText)) { btnD.Text = "D." + nodeD.InnerText; btnD.Tag = nodeD.Attributes["isOK"].Value; btnD.Visible = true; }

            var nodeE = nodeQ.SelectSingleNode(StaticData.AnswerNode + "[@cNo='E']");
            if (nodeE != null && !string.IsNullOrEmpty(nodeE.InnerText)) { btnE.Text = "E." + nodeE.InnerText; btnE.Tag = nodeE.Attributes["isOK"].Value; btnE.Visible = true; }

            var nodeF = nodeQ.SelectSingleNode(StaticData.AnswerNode + "[@cNo='F']");
            if (nodeF != null && !string.IsNullOrEmpty(nodeF.InnerText)) { btnF.Text = "F." + nodeF.InnerText; btnF.Tag = nodeF.Attributes["isOK"].Value; btnF.Visible = true; }

            panel答案.Visible = true;
            //panel答案.Enabled = false;
            timer1.Stop();
        }

        private void AnswerForm_KeyUp(object sender, KeyEventArgs e)
        {
            ///答案ABCDEF 快捷键
            if (e.KeyCode >= Keys.A && e.KeyCode <= Keys.I && panel答案.Enabled)
            {
                if (userIndex == 1)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.A:
                            BtnAnswer_Click(this.btnA, null);
                            break;
                        case Keys.B:
                            BtnAnswer_Click(this.btnB, null);
                            break;
                        case Keys.C:
                            BtnAnswer_Click(this.btnC, null);
                            break;
                    }
                }
                else if (userIndex == 2)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.D:
                            BtnAnswer_Click(this.btnA, null);
                            break;
                        case Keys.E:
                            BtnAnswer_Click(this.btnB, null);
                            break;
                        case Keys.F:
                            BtnAnswer_Click(this.btnC, null);
                            break;
                    }
                }
                else if (userIndex == 3)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.G:
                            BtnAnswer_Click(this.btnA, null);
                            break;
                        case Keys.H:
                            BtnAnswer_Click(this.btnB, null);
                            break;
                        case Keys.I:
                            BtnAnswer_Click(this.btnC, null);
                            break;
                    }
                }

            }
            ///案件抢答
            if (e.KeyCode >= Keys.F1 && e.KeyCode <= Keys.F3 && isQD)
            {
                lock ("lockFA")
                {
                    if (Countdown != 0)
                    {
                        return;
                    }
                    isQD = false;
                    //this.KeyUp -= AnswerForm_KeyUp;
                    CountdownSY = 30;
                    timer2.Start();
                    panel答案.Enabled = true;
                    switch (e.KeyCode)
                    {
                        case Keys.F1:
                            {
                                soundplayer.SoundLocation = StaticData.soundc1;
                                //播放抢答成功音乐
                                userIndex = 1;
                            }
                            break;
                        case Keys.F2:
                            { userIndex = 2; soundplayer.SoundLocation = StaticData.soundc2; }
                            break;
                        case Keys.F3:
                            { userIndex = 3; soundplayer.SoundLocation = StaticData.soundc3; }
                            break;
                        default:
                            break;
                    }
                    soundplayer.Load();
                    soundplayer.Play();
                }
            }
        }

        private void Timer2_Tick(object sender, EventArgs e)
        {
            if (CountdownSY > 0)
            {
                CountdownSY--;
                labelCDown.Text = CountdownSY.ToString();
                return;
            }
            timer2.Stop();
            //MessageBox.Show("回答超时！");
            BtnAnswer_Click(new Button(), null);
        }


        /// <summary>
        /// 计算当前的得分
        /// </summary>
        /// <param name="sNum"></param>
        public void CountNum(double sNum)
        {
            switch (userIndex)
            {
                case 1:
                    labelNo1.Text = (Convert.ToDouble(labelNo1.Text) + sNum).ToString();
                    break;
                case 2:
                    labelNo2.Text = (Convert.ToDouble(labelNo2.Text) + sNum).ToString();
                    break;
                case 3:
                    labelNo3.Text = (Convert.ToDouble(labelNo3.Text) + sNum).ToString();
                    break;
                case 4:
                    labelNo4.Text = (Convert.ToDouble(labelNo4.Text) + sNum).ToString();
                    break;
                case 5:
                    labelNo5.Text = (Convert.ToDouble(labelNo5.Text) + sNum).ToString();
                    break;
                case 6:
                    labelNo6.Text = (Convert.ToDouble(labelNo6.Text) + sNum).ToString();
                    break;
                case 7:
                    labelNo7.Text = (Convert.ToDouble(labelNo7.Text) + sNum).ToString();
                    break;
                case 8:
                    labelNo8.Text = (Convert.ToDouble(labelNo8.Text) + sNum).ToString();
                    break;
                default:
                    break;
            }
        }


        #region initData

        private void initData()
        {
            labelNo1.Text = "0";
        }

        #endregion

        private void 返回ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AnswerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBoxHelper.IsWorking = false;
        }
    }
}
